#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: wang_chao03
@project: pyraft
@file: server
@time: 2023/2/28
"""

import selectors
import asyncio
import sys
from datetime import datetime

from pyraft.server import start, stop
from pyraft.state import State


async def main(index, loop=None):
    server = await start(
        servers='10.201.38.14:28091,10.201.38.14:28092,10.201.38.14:28093', current_server_index=index or 0,
        loop=loop
    )
    # try:
    while True:
        await asyncio.sleep(5)
        if (index == 0 and State.get_leader() == State.get_server_id('10.201.38.14', 28091)) \
                or (index == 1 and State.get_leader() == State.get_server_id('10.201.38.14', 28092)) \
                or (index == 2 and State.get_leader() == State.get_server_id('10.201.38.14', 28093)):
            k = f'test: {datetime.now().strftime("%Y%m%d%H%M")}'
            v = f'{datetime.now().strftime("%H:%M:%S")}'
            print(f'come here, leader is {State.get_leader()}, start to set value: {k}')
            await State.set_value(k, v)
            print(f'come here, leader is {State.get_leader()}, end to set value: {k}')
            result = await State.get_value(k)
            print(f'>>>>>>get_value: {k} = {result}')
    # except KeyboardInterrupt:
    #     # await asyncio.gather(*asyncio.all_tasks(loop))
    #     server.stop()


if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser()
    parser.add_argument('-i', '--index', help="Current server's index", type=int, default=0)
    args = parser.parse_args()
    try:
        if sys.platform == 'win32':
            selector = selectors.SelectSelector()
            loop = asyncio.SelectorEventLoop(selector)
            asyncio.set_event_loop(loop)
        else:
            loop = asyncio.get_event_loop()
        loop.run_until_complete(main(args.index, loop=loop))
    except KeyboardInterrupt:
        stop()
